package com.me.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.me.entity.PaperQuestion;
import com.me.entity.StudentPaper;
import com.me.service.ConfigService;
import com.me.service.PaperQuestionService;
import com.me.service.QuestionLibService;
import com.me.service.StudentPaperService;
import com.me.util.EasyUIFormat;
import com.me.vo.Answer;

@Controller
@RequestMapping("/studentPaper")
public class StudentPaperController extends BaseController {
	/**
	 * 注入业务组件
	 */
	@Resource
	private StudentPaperService studentPaperService;
	@Resource
	private ConfigService configService;
	@Resource
	private PaperQuestionService paperQuestionService;
	@Resource
	private QuestionLibService questionLibService;
	
	/**
	 * 跳转到studentPaper主页
	 */
	@RequestMapping("/index.do")
	public String toIndex(){
		return "admin/main/student_paper";
	}
	
	/**
	 * 查询所有考生试卷
	 */
	@RequestMapping("/queryPage.do")
	@ResponseBody
	public Map<String, Object> queryPage(StudentPaper studentPaper){
		List<StudentPaper> papers = studentPaperService.query(studentPaper);
		return EasyUIFormat.formatEntities(papers);
	}
	
	/**
	 * 更新考生试卷的状态（开始考试）
	 */
	@RequestMapping("/updateState.do")
	@ResponseBody
	public Map<String, Object> update(StudentPaper studentPaper, HttpSession session){
		try {
			LOG.info("--------修改记录：" + studentPaper + "--------");
			// 获取session中的学生记录
			StudentPaper stuPaper = (StudentPaper) session.getAttribute("student");
			LOG.info("-------------Session中的试卷信息：" + stuPaper + "-------------");
			if(studentPaper.getPaperState() != null){
				stuPaper.setPaperState(studentPaper.getPaperState());
				// 设置问答题分数，选择题分数，总分数，成绩等级为空
				stuPaper.setChoiceStudentAnswer(null);
				stuPaper.setQuestionScore(null);
				stuPaper.setTotalScore(null);
				stuPaper.setScoreLevel(null);
				session.setAttribute("student", stuPaper);
				// 执行更新操作
				studentPaperService.update(stuPaper);
				return messageSuccess();
			} else{
				return messageFailure("试卷状态为空", "更新试卷失败！");
			}
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "更新试卷失败！");
		}
	}
	
	/**
	 * 展示改卷的界面
	 */
	@RequestMapping("/paperShow.do")
	public String paperShow(Integer paperId, Model model){
		LOG.info("-------------改卷操作，试卷编号为：" + paperId + "-------------");
		// 获取问答题的编号和考生答案，分别放入集合中
		List<Integer> questionIds = new ArrayList<>();
		List<String> questionAnswers = new ArrayList<>();
		for(PaperQuestion paperQuestion : paperQuestionService.queryByPaperId(paperId)){
			questionIds.add(paperQuestion.getQuestionId());
			questionAnswers.add(paperQuestion.getStudentAnswer());
		}
		// 根据问答题的编号去题库查询问答题的内容，放入集合中
		List<String> questionContents = new ArrayList<>();
		for(Integer questionId : questionIds){
			questionContents.add(questionLibService.queryById(questionId).getQuestionContent());
		}
		LOG.info("-------------问答题题号：" + questionIds + "-------------");
		LOG.info("-------------问答题题目：" + questionContents + "-------------");
		LOG.info("-------------问答题考生答案：" + questionAnswers + "-------------");
		// 将问答题内容和考生答案转发到页面
		model.addAttribute("paperId", paperId);
		model.addAttribute("questionContents", questionContents);
		model.addAttribute("questionAnswers", questionAnswers);
		return "admin/dialog/paper";
	}
	
	/**
	 * 保存教师改卷的结果
	 */
	@RequestMapping("/savePaper.do")
	@ResponseBody
	public Map<String, Object> savePaper(StudentPaper studentPaper){
		try {
			Integer questionScore = studentPaper.getQuestionScore();
			LOG.info("-------------问答题分数：" + questionScore + "-------------");
			// 从数据库查询这条记录
			studentPaper = studentPaperService.queryById(studentPaper.getId());
			studentPaper.setQuestionScore(questionScore);
			// 获取选择题分数和平时成绩，计算总分
			Integer choiceScore = studentPaper.getChoiceScore();
			Integer regularScore = studentPaper.getRegularScore();
			if(choiceScore != null && regularScore != null){
				Integer totalScore = choiceScore + regularScore + questionScore;
				if(totalScore > 100){
					return messageFailure("总成绩超过了100分！", "改卷失败！");
				}
				studentPaper.setTotalScore(totalScore);
				switch (totalScore/10) {
				case 10:
				case 9:
					studentPaper.setScoreLevel(1);
					break;
				case 8:
					studentPaper.setScoreLevel(2);
					break;
				case 7:
					studentPaper.setScoreLevel(3);
					break;
				case 6:
					studentPaper.setScoreLevel(4);
					break;
				default:
					studentPaper.setScoreLevel(5);
					break;
				}
			}
			// 更新这条记录
			studentPaperService.update(studentPaper);
			return messageSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return messageFailure(e.getMessage(), "改卷失败，请联系技术支持！");
		}
	}
	
	/**
	 * 教师删除考生试卷
	 */
	@RequestMapping("/deletePaper.do")
	@ResponseBody
	public Map<String, Object> deletePaper(Integer paperId){
		try {
			LOG.info("-------------删除试卷：" + paperId + "-------------");
			// 执行删除操作
			studentPaperService.delete(paperId);
			return messageSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return messageFailure(e.getMessage(), "删除试卷失败，请联系技术支持！");
		}
	}
	
	/**
	 * 删除全部
	 */
	
	
	/**
	 * 教师允许考生重考
	 */
	@RequestMapping("/allowReExaming.do")
	@ResponseBody
	public Map<String, Object> allowReExaming(StudentPaper studentPaper){
		try {
			LOG.info("-------------允许重考：" + studentPaper + "-------------");
			studentPaper = studentPaperService.queryById(studentPaper.getId());
			studentPaper.setPaperState(2);
			// 执行更新操作
			studentPaperService.update(studentPaper);
			return messageSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return messageFailure(e.getMessage(), "操作失败，请联系技术支持！");
		}
	}
	
	/**
	 * 教师修改平时成绩
	 */
	@RequestMapping("/modifyRegularScore.do")
	@ResponseBody
	public Map<String, Object> modifyRegularScore(StudentPaper studentPaper){
		try {
			Integer regularScore = studentPaper.getRegularScore();
			LOG.info("-------------修改平时成绩：" + studentPaper + "-------------");
			studentPaper = studentPaperService.queryById(studentPaper.getId());
			studentPaper.setRegularScore(regularScore);
			// 查询其它几项成绩，计算总分
			Integer choiceScore = studentPaper.getChoiceScore();
			Integer questionScore = studentPaper.getQuestionScore();
			if(choiceScore != null && questionScore != null){
				Integer totalScore = choiceScore + regularScore + questionScore;
				if(totalScore > 100){
					return messageFailure("总成绩超过了100分！", "修改平时成绩失败！");
				}
				studentPaper.setTotalScore(totalScore);
				switch (totalScore/10) {
				case 10:
				case 9:
					studentPaper.setScoreLevel(1);
					break;
				case 8:
					studentPaper.setScoreLevel(2);
					break;
				case 7:
					studentPaper.setScoreLevel(3);
					break;
				case 6:
					studentPaper.setScoreLevel(4);
					break;
				default:
					studentPaper.setScoreLevel(5);
					break;
				}
			}
			// 执行更新操作
			studentPaperService.update(studentPaper);
			return messageSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return messageFailure(e.getMessage(), "操作失败，请联系技术支持！");
		}
	}
	
	
	/**
	 * 考生提交试卷
	 */
	@RequestMapping("/submitPaper.do")
	@ResponseBody
	public Map<String, Object> submitPaper(Answer answer, HttpSession session){
		// 获取session中的学生记录
		StudentPaper studentPaper = (StudentPaper) session.getAttribute("student");
		LOG.info("-------------Session中的试卷信息：" + studentPaper + "-------------");
		try {
			LOG.info("--------提交试卷：" + answer + "--------");
			/*
			 * 解析选择题答案
			 */
			// 封装最终的考生选择题答案串
			StringBuilder result = new StringBuilder();
			// 查找该试卷的题号串
			String[] choiceIds = studentPaperService.getPaperChoiceIds(studentPaper.getId()).split(",");
			int len = choiceIds.length;
			// 根据考生题号串和试卷题号串对比，生成考试答案串
			Map<?, ?> choiceAnswerMap = new ObjectMapper().readValue(answer.getChoiceAnswer(), Map.class);
			for(int i = 0; i < len; i++){
				if(i < len - 1){
					result.append(choiceAnswerMap.get(choiceIds[i]) + ",");
				} else{
					result.append(choiceAnswerMap.get(choiceIds[i]));
				}
			}
			LOG.info("--------考生的选择题答案串为：" + result + "--------");
			// 将考生答案串更新到session中
			studentPaper.setChoiceStudentAnswer(result.toString());
			
			/*
			 * 根据考生答案串和正确答案串，给出选择题的分数
			 */
			// 记录最终的选择题分数
			int choiceTotalScore = 0;
			// 获取每道选择题的分数
			Integer choiceScore = configService.getChoiceScore();
			// 拆分考生答案串和正确答案串
			String[] choiceAnswersFromStu = result.toString().split(",");
			String[] choiceAnswers = studentPaperService.getPaperChoiceAnswers(studentPaper.getId()).split(",");
			// 系统自动判分
			for(int i = 0; i < len; i++){
				if(choiceAnswers[i].equals(choiceAnswersFromStu[i])){
					choiceTotalScore  += choiceScore;
				}
			}
			LOG.info("--------考生的选择题分数为：" + choiceTotalScore + "--------");
			// 将分数更新到session中
			studentPaper.setChoiceScore(choiceTotalScore);
			
			// 将试卷状态设置成3-已提交考试
			studentPaper.setPaperState(3);
			
			// 执行更新，与session中的试卷信息同步
			LOG.info("-------------更新试卷信息：" + studentPaper + "-------------");
			studentPaperService.update(studentPaper);
			
			/**
			 * 解析问答题的答案
			 */
			// 封装最终的考生问答题答案串
			Map<?, ?> questionAnswerMap = new ObjectMapper().readValue(answer.getQuestionAnswer(), Map.class);
			LOG.info("--------考生的问答题答案串为：" + questionAnswerMap + "--------");
			for(Object key : questionAnswerMap.keySet()){
				// 根据试卷编号和问答题编号，查找唯一的一条绑定信息
				PaperQuestion paperQuestion = paperQuestionService.findOne(studentPaper.getId(), Integer.parseInt(key.toString()));
				// 设置考试答案
				String studentAnswer = questionAnswerMap.get(key) + "";
				if("".equals(studentAnswer)){
					studentAnswer = studentAnswer + "该考生未作答！";
				}
				paperQuestion.setStudentAnswer(studentAnswer);
				// 执行更新操作
				paperQuestionService.updateAnswer(paperQuestion);
			}
			return messageSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return messageFailure(e.getMessage(), "提交试卷失败！");
		}
	}
}
